#pragma once
#include <functional>
#include "InetAddr.hpp"
#include <string>
#define ListenConnection 0
#define NormalConnection 1

class Connection;
class Reactor;
using Handler_t = std::function<void(Connection *conn)>;

// 后面的服务器 都以connection为单位进行传递，处理任务
class Connection
{
public:
    Connection(int sockfd) : _sockfd(sockfd)
    {
    }
    int Sockfd()
    {
        return _sockfd;
    }
    void RegisterHandler(Handler_t handler_recver, Handler_t handler_sender, Handler_t handler_excepter)
    {
        _handler_recver = handler_recver;
        _handler_sender = handler_sender;
        _handler_excepter = handler_excepter;
    }
    void SetEvent(uint32_t events)
    {
        _events = events;
    }
    uint32_t GetEvents()
    {
        return _events;
    }
    void SetConnectionType(int type)
    {
        _type = type;
    }
    void SetType(int type)
    {
        _type = type;
    }
    int GetType()
    {
        return _type;
    }
    void SetReactor(Reactor *r)
    {
        _R = r;
    }
    void SetAddr(InetAddr addr)
    {
        _addr = addr;
    }
    void AppendInBuffer(const std::string &in)
    {
        _inbuffer += in;
    }
    void AppendOutBuffer(std::string &out)
    {
        _outbuffer += out;
    }
    std::string &InBuffer()
    {
        return _inbuffer;
    }
    std::string &OutBuffer()
    {
        return _outbuffer;
    }
    void DiscardBuffer(int n)
    {
        _outbuffer.erase(0, n);
    }
    void Close()
    {
        if (_sockfd >= 0)
            ::close(_sockfd);
    }
    ~Connection()
    {
    }

private:
    int _sockfd;
    uint32_t _events;
    std::string _inbuffer; // 充当缓冲区
    std::string _outbuffer;
    int _type;

public:
    Handler_t _handler_recver;   // 处理读取
    Handler_t _handler_sender;   // 处理写入
    Handler_t _handler_excepter; // 处理异常

    Reactor *_R; // 指向自己所属的reactor
    InetAddr _addr;
};